// 设置权限
import router from '@/router'
import store from '@/store'
import { asyncRoutes } from '@/router'
const whiteList = ['/login', '/404']
// 路由前置守卫
router.beforeEach(async(to, from, next) => {
  if (store.getters.token) {
    if (to.path === '/login') {
      next('/')
    } else {
      if (!store.getters.userId) {
        const res = await store.dispatch('user/asyncUserInfo')
        console.log(res)
        const menus = res.data.roles.menus
        // console.log(menus, asyncRoutes)
        const filterRoutes = asyncRoutes.filter(route => {
          return menus.includes(route.children[0].name)
        })
        console.log(filterRoutes)
        router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }])
        store.commit('menu/setmenuList', filterRoutes)
        next({
          ...to, // next({ ...to })的目的,是保证路由添加完了再进入页面 (可以理解为重进一次)
          replace: true // 重进一次, 不保留重复历史
        })
        return
      }
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})
